package com.iwords.android;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity {
    private boolean emailValid = false;
    private boolean passwordValid = false;
    private boolean passwordConfirmValid = false;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		
	    //用户email，填写后，检查是否可用
	    final EditText email = (EditText)findViewById(R.id.register_email);
	    email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				//System.out.println("email.View.OnFocusChangedListener() hasFocus="+hasFocus);
				if(hasFocus) return;
				validEmail();
				if(emailValid){
					email.setTextColor(getResources().getColor(R.color.text_color_green));
					emailValid = true;
				}else{
					emailValid = false;
					email.setTextColor(getResources().getColor(R.color.text_color));//red
					displayMessage("Email不合法或已被占用。");
				}
			}
		});
	    //用户password，填写后，检查是否为空
	    EditText password = (EditText)findViewById(R.id.register_password);
	    password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				//System.out.println("password.View.OnFocusChangedListener() hasFocus="+hasFocus);
				if(hasFocus) return;
				validPassword();
			}
		});
	    //用户password_confirm，填写后，检查两次密码是否一致
	    EditText password_confirm = (EditText)findViewById(R.id.register_password_confirm);
	    password_confirm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus) return;
				validPasswordConfirm();
			}
		});
	    try{
	    	initRegisterInfo();
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	}
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}
	private void validPasswordConfirm(){
		EditText password = (EditText)findViewById(R.id.register_password);
		EditText password_confirm = (EditText)findViewById(R.id.register_password_confirm);
		String password_confirmText = password_confirm.getText().toString();
		String passwordText = password.getText().toString();
		if(passwordText!=null && passwordText.equals(password_confirmText)){
			password_confirm.setTextColor(getResources().getColor(R.color.text_color_green));
			passwordConfirmValid = true;
		}else{
			password_confirm.setTextColor(getResources().getColor(R.color.text_color));
			displayMessage("两次输入密码不一致。");
			passwordConfirmValid = false;
		}
	}
	private void validPassword(){
		EditText password = (EditText)findViewById(R.id.register_password);
		String passwordText = password.getText().toString();
		if(passwordText!=null && passwordText.trim().length()>0){
			password.setTextColor(getResources().getColor(R.color.text_color_green));
			passwordValid = true;
		}else{
			password.setTextColor(getResources().getColor(R.color.text_color));
			displayMessage("密码不能为空，且首尾空格会被忽略。");
			passwordValid = false;
		}
	}
	private void initRegisterInfo() throws Exception{
		if(!getIntent().hasExtra("fromConfigMenu")) return;
	    //如果是注册信息编辑，则从服务器加载注册信息，然后做初始化
	    JSONObject info = this.getRegisterInfo();
	    //email 不让修改
	    EditText email = ((EditText)findViewById(R.id.register_email));
	    email.setEnabled(false);
	    if(info.has("username")){
	    	email.setText(info.getString("username"));
	    	email.setTextColor(getResources().getColor(R.color.text_color_green));
		    //System.out.println(info.getString("username"));
	    }
	    EditText password = ((EditText)findViewById(R.id.register_password));
	    EditText password_confirm = ((EditText)findViewById(R.id.register_password_confirm));
	    if(info.has("password")){
	    	password.setText("");
	    	password_confirm.setText("");	    	
	    }
		Button confirm = (Button)findViewById(R.id.register);
		confirm.setText("更  新");
		confirm.setEnabled(true);
	}
	/**查询用户的注册信息。*/
	private JSONObject getRegisterInfo(){
		String href = this.getResources().getString(R.string.user_find);
		HttpPost request = new HttpPost(href + ((IWordsApp) getApplicationContext()).getUser().getUserid());
		//System.out.println("Register.valid()! href="+href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if(success) {
				return jSONObject.getJSONObject("defaultValue");
			}else{
				this.displayMessage(CodeUtils.decode(jSONObject.getString("message")));
			}
		} catch(Exception e){
			//e.printStackTrace();
			this.displayMessage(e.getMessage());
		}
		return null;
	}

     /**用户点击注册后，提交注册信息。*/
    public void registerHandler(View view) {
    	this.vibrate();
    	this.validPassword();
    	this.validPasswordConfirm();
    	//System.out.println("Register.registerHandler() getIntent().hasExtra(\"fromConfigMenu\") = "+getIntent().hasExtra("fromConfigMenu"));
		if(!getIntent().hasExtra("fromConfigMenu")) {
			this.validEmail();
		}
		if (!this.emailValid) {
			displayMessage("email信息不合规范或已被注册。");
			return;
		}
    	if(!this.passwordValid){
    		displayMessage("请填写密码信息。");
    		return;
    	}
    	if(!this.passwordConfirmValid){
    		displayMessage("密码确认信息有误。");
    		return;
    	}
    	if(getIntent().hasExtra("fromConfigMenu")) {
    		if(update()){
    			displayMessage("更新成功。");
    			this.finish();
    		}else{
    			displayMessage("更新失败。");
    		}
    		return;
    	}
    	if(register()){
    		displayMessage("注册成功，选择课本开始。");
    		//直接将用户信息写入手机，下次自动登录
    		saveSettings();
    		Intent intent = new Intent(this, IWords.class);
    		this.startActivity(intent);
    	}else{
    		displayMessage("注册失败。");
    	}
	}
	private boolean update(){
		String href = this.getResources().getString(R.string.user_update);
		//System.out.println("Register.valid()! href="+href);
		try {
			
			href = href  + paramString() + "&userid="+((IWordsApp) getApplicationContext()).getUser().getUserid();
			//System.out.println("Register.valid()! href="+href);
			HttpPost request = new HttpPost(href);

			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据	
			
			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			//System.out.println("Register.valid() retSrc="+retSrc);
			retSrc = CodeUtils.decode(retSrc);
			//System.out.println("Register.valid() after decode retSrc="+retSrc);
			// 生成 JSON 对象
			JSONObject jSONObject = new JSONObject(retSrc);
			boolean success = jSONObject.getBoolean("isSuccess");
			return success;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
    }
    
    
	private void saveSettings(){
		SharedPreferences settings = this.getSharedPreferences(IWords.class.getName(), MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();  
		String email = ((EditText)findViewById(R.id.register_email)).getText().toString();
		String password = ((EditText)findViewById(R.id.register_password)).getText().toString();
		editor.putBoolean("autoLogin", true);
		editor.putString("username", email);
		editor.putString("password", password);
		editor.remove("currentlib");//新注册用户不应该有currentlib属性，移除这个属性，保证新注册用户可以进入词库课本选择界面
		editor.commit();  
		//当从旧用户注册新用户，重新开始时，需要清理掉上一个用户的驻留内存数据
		//WordsKnownManager.clear();
		IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
		iWordsApp.clear();
	}

	private String paramString(){
		String email = ((EditText)findViewById(R.id.register_email)).getText().toString();
		String password = ((EditText)findViewById(R.id.register_password)).getText().toString();
		// 绑定到请求 Entry
		String paramStr = "&username="+CodeUtils.encode(email);
		paramStr += "&password="+CodeUtils.encode(password);
		// 有用户昵称不能为空的限制，先添加一个绕过
		paramStr += "&nickname=nickname";
		return paramStr;
	}
	private boolean register(){
		String href = this.getResources().getString(R.string.user_register);
		//System.out.println("Register.valid()! href="+href);
		try {
			
			href = href  + paramString();
			//System.out.println("Register.valid()! href="+href);
			HttpPost request = new HttpPost(href);

			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据	
			
			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			//System.out.println("Register.valid() retSrc="+retSrc);
			retSrc = CodeUtils.decode(retSrc);
			//System.out.println("Register.valid() after decode retSrc="+retSrc);
			// 生成 JSON 对象
			JSONObject jSONObject = new JSONObject(retSrc);
			boolean success = jSONObject.getBoolean("isSuccess");
			return success;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
    }
    
	private void validEmail(){
		//System.out.println("Register.validEmail()");
		//new Exception().printStackTrace();
		if(getIntent().hasExtra("fromConfigMenu")) {
			this.emailValid = true;
			return;//修改时，email只读，无需验证
		}
		EditText emailText = (EditText)findViewById(R.id.register_email);
		String email =emailText.getText().toString();
		if(!isMail(email)) return;
		String href = this.getResources().getString(R.string.user_email_valid);
		href+=email;
		HttpPost request = new HttpPost(href);
		//System.out.println("Register.valid()! href="+href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据	
			
			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			//System.out.println("Register.valid() retSrc="+retSrc);
			retSrc = CodeUtils.decode(retSrc);
			//System.out.println("Register.valid() after decode retSrc="+retSrc);
			// 生成 JSON 对象
			JSONObject jSONObject = new JSONObject(retSrc);
			boolean success = jSONObject.getBoolean("isSuccess");
			if(success){
				emailValid = jSONObject.getBoolean("defaultValue");
			}else{
				emailValid = false;
			}
		}catch(Exception e){
			e.printStackTrace();
			emailValid = false;
		}
	}
	
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_SHORT);
		t1.show();
	}
	private boolean isMail(String str){
        String   check   =   "^([a-z0-9A-Z]+[-|\\._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";   
        Pattern   regex   =   Pattern.compile(check);   
        Matcher   matcher   =   regex.matcher(str);   
        boolean   isMatched   =   matcher.matches();   
        if(isMatched){   
            return true;  
        }else{   
            return false;
        }    
    }
	
	public void onResume() {
		super.onResume(); 
		com.mobclick.android.MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause(); 
		com.mobclick.android.MobclickAgent.onPause(this);
	}
	
}
